package com.example.treasureadmin.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.treasureadmin.entity.MsgEntity;
import com.example.treasureadmin.model.MapModel;
import com.example.treasureadmin.service.MapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/treasure-admin")
public class MapController {
    @Autowired
    private MapService mapService;
    private final static String[] allowFileType = new String[]{".bmp", ".jpg", ".jpeg", ".png", ".gif"};

    @GetMapping("/map/all")
    public MsgEntity getAll(){
        List<MapModel> all = mapService.getAll();
        return new MsgEntity("200","SUCCESS",all);
    }

    @PostMapping("map/add")
    public MsgEntity addMap(@RequestParam("file") MultipartFile file,@RequestParam("lng") String lng,
                              @RequestParam("lat") String lat) throws IOException {

        if (file.isEmpty()){
            return new MsgEntity("200","ERROR","文件为空");
        }
        else{
            if (!Objects.requireNonNull(file.getOriginalFilename()).contains(".")){
                return new MsgEntity("200","ERROR","文件解析异常");
            }
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (suffix.isEmpty()|| !Arrays.asList(allowFileType).contains(suffix)){
                return new MsgEntity("200","ERROR","文件格式错误");
            }
            //上传到oss
            String result = mapService.uploadImage(file.getInputStream(), suffix);
            mapService.addMap(lng,lat,result);
            return new MsgEntity("200","SUCCESS","添加成功");
        }
    }

    @PutMapping("map/{id}")
    public MsgEntity changeStatus(@RequestBody JSONObject requestBody,@PathVariable("id") Integer id)
    {
        int status = requestBody.getInteger("status");
        mapService.changeStatus(id,status);
        return new MsgEntity("200","SUCCESS","修改成功");
    }

    @GetMapping("/map/status/{status}")
    public MsgEntity getStateOrders(@PathVariable("status") Integer status){
        List<MapModel> all = mapService.getStatusMap(status);
        return new MsgEntity("200","SUCCESS",all);
    }
}
